package com.dgut.lotterySystem.controller;

import com.dgut.lotterySystem.common.pojo.CommonResult;
import com.dgut.lotterySystem.common.utils.JacksonUtil;
import com.dgut.lotterySystem.controller.param.CreatePrizeParam;
import com.dgut.lotterySystem.controller.param.PageParam;
import com.dgut.lotterySystem.controller.result.PrizeInfoListResult;
import com.dgut.lotterySystem.service.dto.PageInfoListDTO;
import com.dgut.lotterySystem.service.dto.PrizeInfoDTO;
import com.dgut.lotterySystem.service.impl.PictureServiceImpl;
import com.dgut.lotterySystem.service.impl.PrizeServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.stream.Collectors;

@RestController
@RequestMapping("/prize")
public class PrizeController {

    @Autowired
    private PictureServiceImpl pictureService;
    @Autowired
    private static final Logger logger= LoggerFactory.getLogger(PrizeController.class);
    @Autowired
    private PrizeServiceImpl prizeService;

    @PostMapping("/uploadPic")
    public String uploadPicture(MultipartFile picture){
        return pictureService.savePicture(picture);
    }
    @PostMapping("/createPrize")
    public CommonResult<Long> createPrize(@Validated @RequestPart("param") CreatePrizeParam param,
                                          @RequestPart("prizePic") MultipartFile prizePic){
        logger.info("createPrize CreatePrizeParam"+ param);
        return CommonResult.success(
                prizeService.createPrize(param,prizePic));
    }

    @GetMapping("/getPrizeInfoList")
    public CommonResult<PrizeInfoListResult> getPrizeInfoList(PageParam param){
        logger.info("getPrizeInfoList param"+ JacksonUtil.writeValueAsString(param));
        PageInfoListDTO<PrizeInfoDTO> pageList=prizeService.getPageInfoList(param);
        return CommonResult.success(converterPageInfoList(pageList));
    }

    private PrizeInfoListResult converterPageInfoList(PageInfoListDTO<PrizeInfoDTO> pageList) {
        if(pageList==null){
            return null;
        }
        PrizeInfoListResult result=new PrizeInfoListResult();
        result.setTotal(pageList.getTotal());
        result.setRecords(pageList.getRecords().stream().map(prizeInfoDTO->{
                PrizeInfoListResult.PrizeInfo prizeInfo=new PrizeInfoListResult.PrizeInfo();
                prizeInfo.setPrizeId(prizeInfoDTO.getId());
                prizeInfo.setPrizeName(prizeInfoDTO.getName());
                prizeInfo.setDescription(prizeInfoDTO.getDescription());
                prizeInfo.setPrice(prizeInfoDTO.getPrice());
                prizeInfo.setImageUrl(prizeInfoDTO.getImageUrl());
                return prizeInfo;
        }).collect(Collectors.toList()));
        return result;
    }
}
